package concurrents.consumerproduce;

public class ProductList {

	int index = 0;
	
	Product[] productList = new Product[6];
	
	public synchronized void push(Product product){
		while(index == productList.length){	//仓库满了
			try{
				System.out.println(" " + product.getProducedBy() + "is waiting.");
				wait();
			}catch(InterruptedException ie){
				ie.printStackTrace();
			}
		}
		//notify以后
		productList[index] = product;
		index ++;
		System.out.println(index + " " + product.getProducedBy() + " 生产了：" + product);
		
		notifyAll();
		System.out.println("  " + product.getProducedBy() + " sent a notifyAll().");
	}
	
	public synchronized Product pop(String consumerName){
		while(index == 0){
			try{
				System.out.println("  " + consumerName + " is waiting");
				wait();
			}catch(InterruptedException ie){
				ie.printStackTrace();
			}
		}
		
		index--;
		Product product = productList[index];
		product.setConsumedBy(consumerName);
		System.out.println(index + " " + product.getConsumedBy() + " 消费了：" + product);
		
		notifyAll();
		System.out.println(" " + consumerName + " sent a notifyAll().");
		return product;
	}
	
}
